DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only
A3Tech logo

Introduction to Python Programming · A3Tech

Module 6

Today you will

Give the shop a memory: a database that keeps every product and sale after the program closes.

  1. Explain why a database beats a dictionary for a shop that runs every day.
  2. Describe a table, a row and a column, and see them in DB Browser.
  3. Import the shop_db helper module and call its functions.
  4. Ask the database your own questions with SELECT ... WHERE.
  5. Use what the database gives back with your Module 5 lists, dictionaries and loops.

Deep dive A: why do we need a database?

In Module 5 the price list was a dictionary. Run this, then run it again:

forgets.py
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
products["Bread Pudding"] = 6.00      # add a new product
print(products)
Output
{'Beef Patty': 5.0, 'Coconut Tart': 4.0, 'Bread Pudding': 6.0}

It prints the same thing every time. Bread Pudding isn't "still there" from the last run: the program adds it again, because when a program ends, its variables, lists and dictionaries are wiped. They only live in the computer's memory while the program is running.

A real shop needs to remember what it sold yesterday. A database saves the data in a file, so it's still there after the program closes, after you shut down Thonny, even after the computer restarts.

Deep dive B: tables, rows and columns

A database holds tables. A table looks like a spreadsheet tab. Our shop has two: products and sales. Here's the products table:

idnamepricestock
1Beef Patty5.040
2Cheese Patty5.030
3Coconut Tart4.025
4Sorrel Drink3.520
  • A row is one record: one product.
  • A column is one kind of information: every product's price.
  • id is a number the database gives each row, so every product has its own label even if two had the same name.

This should feel familiar. One row is just like a Module 5 dictionary, and the whole table is like a list of dictionaries:

rows_as_dicts.py
row = {"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40}
print(row["name"], "costs", row["price"])

table = [
    {"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40},
    {"id": 2, "name": "Cheese Patty", "price": 5.0, "stock": 30},
]
print(len(table), "rows")
Output
Beef Patty costs 5.0
2 rows
rows_as_dict_expanded.py
row = {"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40}
print(row["name"], "costs", row["price"])

table = [
    {"id": 1, "name": "Beef Patty", "price": 5.0, "stock": 40},
    {"id": 2, "name": "Cheese Patty", "price": 5.0, "stock": 30},
    {"id": 3, "name": "Bottled Water", "price": 4.50, "stock": 30}
]
print(len(table), "rows")

print(table[0]["name"], "price $",table[0]["price"], "amount in stock =", table[0]["stock"])
    #this prints the item that we targeted

for item in table:
    print(item["name"], "price $", item ["price"], "amount in stock =", item["stock"])
    #This loops through the dictionary and prints each item
Output
Beef Patty costs 5.0
3 rows
Beef Patty price $ 5.0 amount in stock = 40
Beef Patty price $ 5.0 amount in stock = 40
Cheese Patty price $ 5.0 amount in stock = 30
Bottled Water price $ 4.5 amount in stock = 30
>>> 

Deep dive C: meet shop_db - our helper module

Talking to a database takes some extra code: connect to the file, run the command, save, close. To keep today about the ideas, that code lives in a ready-made file, shop_db.py. You import it, the same way you've imported Streamlit, and call its functions.

FunctionWhat it does
shop_db.setup()Creates shop.db with the starter products. Safe to run every time.
shop_db.get_products()Every product, as a list of dictionaries
shop_db.find_product(name)One product as a dictionary, or None
shop_db.add_product(name, price, stock)Adds a product, gives back a message
shop_db.record_sale(name, qty)Saves a sale and takes the stock down, gives back a message
shop_db.query(sql)Ask your own SQL question (Deep dive E)
shop_db.reset()Empty the shop and start again
meet_shop_db.py
import shop_db

shop_db.setup()
products = shop_db.get_products()
print(len(products), "products")
print(products[0])

for p in products:
    print(f"{p['name']:<14} EC${p['price']:5.2f}   stock: {p['stock']}")
Output
4 products
{'id': 1, 'name': 'Beef Patty', 'price': 5.0, 'stock': 40}
Beef Patty     EC$ 5.00   stock: 40
Cheese Patty   EC$ 5.00   stock: 30
Coconut Tart   EC$ 4.00   stock: 25
Sorrel Drink   EC$ 3.50   stock: 20

Everything from Module 5 works on what comes back: len(), [0] for the first item, p['name'] to look up a key, and a for loop to go through them all.

Deep dive D: look inside with DB Browser

shop.db is a real file. After running the code above it appears in the same folder. Open it to see the tables:
  1. Open DB Browser for SQLite.
  2. Open Database, then choose shop.db in your course folder.
  3. Click the Browse Data tab.
  4. Pick products from the Table list. There are your rows and columns.
  5. Run a Python program that changes the shop, then press F5 in DB Browser to refresh.

Deep dive E: your first SQL - SELECT ... WHERE

SQL is the language for asking a database questions. You write it as text in quotes and hand it to shop_db.query(), which gives back the matching rows as a list of dictionaries.
first_select.py
import shop_db

cheap = shop_db.query("SELECT name, price FROM products WHERE price < 5")
for p in cheap:
    print(p["name"], p["price"])
Output
Coconut Tart 4.0
Sorrel Drink 3.5
PartMeansLike...
SELECT name, priceWhich columns you wantPicking which keys to print
FROM productsWhich tableWhich list
WHERE price < 5Which rows: only the ones that matchAn if inside the loop (Module 3)

Text values go in single quotes inside the SQL, so they don't clash with the double quotes around the whole command:

select_text.py
import shop_db

tart = shop_db.query("SELECT name, price, stock FROM products WHERE name = 'Coconut Tart'")
print(tart)
Output
[{'name': 'Coconut Tart', 'price': 4.0, 'stock': 25}]

Deep dive F: add a product - data that lasts

shop_db.add_product() saves a new product in the database. Run this once:
add_product.py
import shop_db

print(shop_db.add_product("Bread Pudding", 6.00, 12))
print(shop_db.find_product("Bread Pudding"))
Output
Added Bread Pudding.
{'id': 5, 'name': 'Bread Pudding', 'price': 6.0, 'stock': 12}

Now close the program and run the exact same thing a second time:

add_product.py
import shop_db

print(shop_db.add_product("Bread Pudding", 6.00, 12))
print(shop_db.find_product("Bread Pudding"))
Output
Bread Pudding is already in the shop.
{'id': 5, 'name': 'Bread Pudding', 'price': 6.0, 'stock': 12}

Bread Pudding survived. The program closed, and the database still had it, which is exactly what the dictionary in Deep dive A couldn't do. And the shop won't add a second Bread Pudding: every product name must be unique, just like dictionary keys in Module 5.

Deep dive G: the helper does the heavy lifting

Selling something takes two changes: add a row to sales, and take the stock down in products. shop_db.record_sale() does both, checks you have enough first, and gives back a message.

sell.py
import shop_db

print(shop_db.record_sale("Beef Patty", 3))
print(shop_db.record_sale("Coconut Tart", 30))
print(shop_db.record_sale("Pizza", 1))
print(shop_db.record_sale("Coconut Tart", 2))
print(shop_db.find_product("Coconut Tart"))
Output
Sold 3 x Beef Patty = EC$15.00. 37 left.
Only 25 Coconut Tart left.
Sorry, we don't sell Pizza.
Sold 2 x Coconut Tart = EC$8.00. 23 left.
{'id': 3, 'name': 'Coconut Tart', 'price': 4.0, 'stock': 23}

The last line proves it: Coconut Tart's stock in the database went from 25 down to 23.

Deep dive H: back to Module 5

The database gives back lists and dictionaries, so everything you learned in Module 5 still works. Here the price list comes out of the database into a dictionary, and the Module 5 order total runs on it unchanged:

back_to_module5.py
import shop_db

prices = {}
for p in shop_db.get_products():
    prices[p["name"]] = p["price"]
print(prices)

order = ["Beef Patty", "Sorrel Drink", "Beef Patty"]
total = 0
for item in order:
    total += prices[item]
print(f"Order total: EC${total:.2f}")
Output
{'Beef Patty': 5.0, 'Cheese Patty': 5.0, 'Coconut Tart': 4.0, 'Sorrel Drink': 3.5}
Order total: EC$13.50

1. Set up the shop

Put shop_db.py in your course folder first. Run this, then open shop.db in DB Browser.

01_setup_shop.py
# Module 6 - set up the shop database
# shop_db.py must be in the same folder as this file.
import shop_db

shop_db.setup()
print("Database ready: shop.db")
for p in shop_db.get_products():
    print(f"  {p['name']:<14} EC${p['price']:5.2f}   stock: {p['stock']}")
Output
Database ready: shop.db
  Beef Patty     EC$ 5.00   stock: 40
  Cheese Patty   EC$ 5.00   stock: 30
  Coconut Tart   EC$ 4.00   stock: 25
  Sorrel Drink   EC$ 3.50   stock: 20

2. A till that remembers

The Module 4 till loop, but every sale is saved in the database. Run it, sell a few things, stop it, and run it again: the stock has gone down.

02_till.py
# Module 6 - a till that remembers every sale
import shop_db

shop_db.setup()
print("MENU")
for p in shop_db.get_products():
    print(f"  {p['name']:<14} EC${p['price']:5.2f}  ({p['stock']} left)")

while True:
    name = input("Product (or 'done'): ")
    if name == "done":
        break
    qty = int(input("How many? "))
    print(" ", shop_db.record_sale(name, qty))
Output
MENU
  Beef Patty     EC$ 5.00  (40 left)
  Cheese Patty   EC$ 5.00  (30 left)
  Coconut Tart   EC$ 4.00  (25 left)
  Sorrel Drink   EC$ 3.50  (20 left)
Product (or 'done'): Beef Patty
How many? 3
  Sold 3 x Beef Patty = EC$15.00. 37 left.
Product (or 'done'): Pizza
How many? 1
  Sorry, we don't sell Pizza.
Product (or 'done'): Coconut Tart
How many? 40
  Only 25 Coconut Tart left.
Product (or 'done'): Coconut Tart
How many? 2
  Sold 2 x Coconut Tart = EC$8.00. 23 left.
Product (or 'done'): done
search_by_product_id.py
# Module 6 - a till that remembers every sale
import shop_db

shop_db.setup()
print("MENU")
for p in shop_db.get_products():
    # Fixed the quote nesting inside the f-string by using single quotes for 'id'
    print(f"  {p['id']}. {p['name']:<12} EC${p['price']:5.2f}  ({p['stock']} left)")

while True:
    user_input = input("Product ID (or 'done'): ")
    
    if user_input.lower() == "done":
        break
    
    # Convert the entered ID to an integer
    product_id = int(user_input)
    qty = int(input("How many? "))
    
    # Find the product name that matches the ID entered
    found_name = None
    for p in shop_db.get_products():
        if p["id"] == product_id:
            found_name = p["name"]
            break
            
    if found_name:
        print(" ", shop_db.record_sale(found_name, qty))
    else:
        print("⚠️ Invalid ID, please try again.")
Output
RUN IT AND SEE

3. Extra (fast finishers): reports

Questions a shop owner asks, answered from the database. The low-stock query is a SELECT you could write yourself. The sales report comes ready-made from the helper.

03_shop_reports.py
# Module 6 - answer the shop owner's questions
import shop_db

print("Low stock (under 25):")
low = shop_db.query("SELECT name, stock FROM products WHERE stock < 25")
for p in low:
    print(f"  {p['name']}: {p['stock']} left")

print("Sales by product:")
for row in shop_db.sales_report():
    print(f"  {row['name']:<14} {row['qty']:>3} sold   EC${row['money']:6.2f}")
Output
Low stock (under 25):
  Coconut Tart: 23 left
  Sorrel Drink: 20 left
Sales by product:
  Beef Patty       3 sold   EC$ 15.00
  Coconut Tart     2 sold   EC$  8.00

Bug hunt

This program crashes. Read the last line of the error, fix the bug, run it again.

04_db_bug.py
# BUG HUNT - this program crashes.
# It should list every product under EC$5.
# 1. Run it.  2. Read the LAST line of the error.  3. Fix the bug.
import shop_db

shop_db.setup()
cheap = shop_db.query("SELECT name, prise FROM products WHERE price < 5")
for p in cheap:
    print(p["name"], p["price"])
Hints (open only if stuck)
  1. The error names the problem word. Find it in the code.
  2. Open the products table in DB Browser. What are the columns really called?

Words to know

WordMeaning
DatabaseData saved in a file, so it lasts after the program closes
TableLike a spreadsheet tab: rows and columns
Row / columnOne record (one product) / one kind of information (price)
SQLThe language for asking a database questions
SELECT ... FROM ... WHERERead these columns, from this table, only the rows that match
importBring in another file's functions, like import shop_db
shop.dbThe database file itself, next to your programs

Practice

Homework 6 (5%): my_shop.py

Put your own shop in the database. It must:

Submit your .py file, a screenshot of it running and your DB Browser screenshot, before the next module.

MarkMeans
5Runs and has everything
3Runs with parts missing, or has errors
1Started
0Not submitted

Quiz 6

Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).

1. In a table, what is a row?
2. Which SQL reads data from a table?
3. What does this give back?
shop_db.query("SELECT name FROM products WHERE stock < 30")
4. What does shop_db.get_products() give back?
5. You add Bread Pudding to a Python dictionary AND to shop.db, then close the program. What's still there next time?

ADDITIONAL - STREAMLIT APP - SNEAK PEEK 6

The shop database in a web page. Sell something with the button and it's saved in shop.db for good. The stock table, low-stock warnings and sales chart all read straight from the database.

stock_app.py
# stock_app.py - Module 6 sneak peek: the shop database in the browser
# Run it with:  streamlit run stock_app.py
# shop_db.py must be in the same folder.

import streamlit as st
import shop_db                                                  # Module 6: our own helper module

shop_db.setup()
st.title("Mama J's Stock Room")

names = []
for p in shop_db.get_products():                                # Module 4 loop over a Module 5 list
    names.append(p["name"])

choice = st.selectbox("Sell a product", names)
qty = st.number_input("How many?", min_value=1, value=1, step=1)
if st.button("Record sale"):                                    # Module 3: if
    st.info(shop_db.record_sale(choice, qty))                   # saved to shop.db for good

st.subheader("Stock")
st.dataframe(shop_db.get_products())                            # read again, so it shows the new stock

low = shop_db.query("SELECT name, stock FROM products WHERE stock < 10")      # your own SQL
for p in low:
    st.warning(f"Low stock: {p['name']} ({p['stock']} left)")

st.subheader("Sales so far")
report = shop_db.sales_report()
if report:
    st.bar_chart(report, x="name", y="money")
else:
    st.write("No sales yet - sell something above.")
Output
See the browser. Pick Coconut Tart, set How many? to 2, press Record sale:
Sold 2 x Coconut Tart = EC$8.00. 23 left.
The Stock table updates, and a bar chart of sales appears under "Sales so far".
Close the browser and run it again tomorrow - the sale is still there.